import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Book } from './book.interface';
import { dataBase, Schema } from '../utils/mongoDB';
import { Model, Document } from 'mongoose';
import axios from 'axios';

function initBookSchema() {
  const BookModule = new Schema({
    name: String,
    describe: String || undefined,
    year: Number || undefined,
    author: String || undefined,
  });

  return BookModule;
}

@Injectable()
export class BookService {
  private readonly books: Book[] = [];
  bookModule: Model<Document<any, any, any>>;

  constructor() {
    this.bookModule = dataBase.model('bookModule', initBookSchema());
  }

  findAll() {
    return this.bookModule.find();
  }

  async demoAxios() {
    const resolve = await axios.get('http://localhost:3000/api/hello');

    console.log('让我康康', resolve);

    return resolve.data;
  }

  async findBook(name) {
    const getBook = await this.bookModule.find({ name }).sort({ year: -1 });
    return { code: HttpStatus.OK, data: getBook };
  }

  async addBook(booksData: Book | Book[]) {
    const resolve = await this.bookModule.create(booksData);

    // if (resolve._id) {
    //   throw new HttpException(
    //     {
    //       status: HttpStatus.BAD_GATEWAY,
    //       error: '失败啦, 联系相关人员',
    //     },
    //     HttpStatus.BAD_GATEWAY,
    //   );
    // }

    return { code: HttpStatus.OK, data: resolve };
  }

  async deleteBook(ids: string[]) {
    ids.forEach(async (id) => {
      await this.bookModule.findByIdAndDelete(id);
    });

    return { code: HttpStatus.OK, message: '删除图书成功' };
  }

  async updateBook(ids: string[], book: Book) {
    ids.forEach(async (id) => {
      await this.bookModule.findByIdAndUpdate(id, book);
    });

    return { code: HttpStatus.OK, message: '更改图书成功' };
  }
}
